package com.monkeygroup.mygoplus.ecchat.ui.group;

import android.Manifest;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.monkeygroup.mygoplus.MyGoApplication;
import com.monkeygroup.mygoplus.R;
import com.monkeygroup.mygoplus.base.BaseActivity;
import com.monkeygroup.mygoplus.common.DefinedView.MyDialog;
import com.monkeygroup.mygoplus.common.utils.Tools;
import com.monkeygroup.mygoplus.ecchat.common.utils.FileAccessor;
import com.monkeygroup.mygoplus.ecchat.ui.contact.InviteContactActivity;
import com.monkeygroup.mygoplus.ecchat.ui.contact.entity.ContactMemberDTO;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/5/22.
 */
public class CreateNewGroup extends BaseActivity implements View.OnClickListener {
    private EditText groupname_edit;
    private ImageView new_group_icon;
    private String imageName = "";
    private Bitmap mBitmap = null;
    private Dialog dialog = null, permissionDialog = null;
    private List<ContactMemberDTO> memberList = new ArrayList<>();
    private String friendId = "";
    private final int REQUEST_IMAGE_CAMERA = 11;
    private final int REQUEST_IMAGE_PHOTO = 12;
    private final int REQUEST_CODE_INVITE_MEMBER = 123;
    private final String TAG = "CreateNewGroup";

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_create_group);
    }

    @Override
    public void initView() {
        groupname_edit = (EditText) findViewById(R.id.groupname_edit);
        new_group_icon = (ImageView) findViewById(R.id.new_group_icon);
    }

    @Override
    public void setListener() {
        findViewById(R.id.layout_back).setOnClickListener(this);
        findViewById(R.id.layout_shortcut).setOnClickListener(this);
        findViewById(R.id.btn_invite_friend).setOnClickListener(this);

        new_group_icon.setOnClickListener(this);
    }

    @Override
    public void doEvent() {
        friendId = getIntent().getExtras().getString("friendid");

        Map<String, ContactMemberDTO> members = MyGoApplication.getContacts();
        if (members.containsKey(friendId)) {
            memberList.add(members.get(friendId));
        }

        if (memberList.get(0).getHeadUrl() != null && !memberList.get(0).getHeadUrl().equals("")) {
            ImageLoader.getInstance().displayImage(memberList.get(0).getHeadUrl(), new_group_icon, MyGoApplication.getDefaultDisplayImgOption());
        } else {
            new_group_icon.setImageResource(R.drawable.no_head_icon);
        }
    }

    private void createDialog() {
        if (dialog == null) {
            dialog = new MyDialog(this, R.style.MyDialogTheme, "從相冊", "使用相機", "刪除", new MyDialog.OnThreeButtonClickListener() {
                @Override
                public void firstClick() {
                    dialog.dismiss();

                    requestStoragePermission();
                }

                @Override
                public void secondClick() {
                    dialog.dismiss();

                    requestCameraPermission();
                }

                @Override
                public void thirdClick() {
                    dialog.dismiss();

//                    new_group_icon.setImageBitmap(mBitmap);
                    Toast.makeText(CreateNewGroup.this, "刪除成功", Toast.LENGTH_SHORT).show();
                }
            });
        }
        dialog.show();
    }

    private static final int CAMERA_STORAGE_REQUEST = 103;
    private static final int WRITE_STORAGE_REQUEST = 104;

    // 启动应用的设置
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    private void requestStoragePermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            SharedPreferences sp = Tools.getSharePreferences(CreateNewGroup.this, Tools.PERMISSION_STATUS);
            if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    && !sp.getBoolean(Tools.STORAGE_PERMISSION_STATUS, false)) {
                showAppSettingPermission();
                return;
            }

            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_STORAGE_REQUEST);
        } else {
            takePhoto();
        }
    }

    private void requestCameraPermission() {
        if ((ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
                && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            SharedPreferences sp = Tools.getSharePreferences(CreateNewGroup.this, Tools.PERMISSION_STATUS);
            if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)
                    && !sp.getBoolean(Tools.CAMERA_PERMISSION_STATUS, false)) {
                showAppSettingPermission();
                return;
            }

            if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    && !sp.getBoolean(Tools.STORAGE_PERMISSION_STATUS, false)) {
                showAppSettingPermission();
                return;
            }

            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, CAMERA_STORAGE_REQUEST);
        } else {
            takeCamera();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_STORAGE_REQUEST) {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                takeCamera();
            } else {
                Toast.makeText(CreateNewGroup.this, getResources().getString(R.string.permission_write_open), Toast.LENGTH_SHORT).show();
            }
            SharedPreferences sp = Tools.getSharePreferences(CreateNewGroup.this, Tools.PERMISSION_STATUS);
            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean(Tools.STORAGE_PERMISSION_STATUS, true);
            editor.putBoolean(Tools.CAMERA_PERMISSION_STATUS, true);
            editor.commit();

        } else if (requestCode == WRITE_STORAGE_REQUEST) {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                takePhoto();
            } else {
                Toast.makeText(CreateNewGroup.this, getResources().getString(R.string.permission_write_open), Toast.LENGTH_SHORT).show();
            }

            SharedPreferences sp = Tools.getSharePreferences(CreateNewGroup.this, Tools.PERMISSION_STATUS);
            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean(Tools.STORAGE_PERMISSION_STATUS, true);
            editor.commit();
        }
    }

    private void showAppSettingPermission() {
        if (permissionDialog == null) {
            permissionDialog = new MyDialog(CreateNewGroup.this, R.style.MyDialogTheme, getResources().getString(R.string.permission_camera_setting), getResources().getString(R.string.permission_setting_cancel), getResources().getString(R.string.permission_do_setting), new MyDialog.OnCommonDoubleClickListener() {
                @Override
                public void doLeftClick() {
                    permissionDialog.dismiss();
                }

                @Override
                public void doRightClick() {
                    permissionDialog.dismiss();
                    startAppSettings();
                }
            });

            permissionDialog.show();
        } else {
            permissionDialog.show();
        }
    }

    private void takeCamera() {
        imageName = "IMAGE_" + System.currentTimeMillis() + ".jpg";

        Intent mIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        try {
            File imageFile = new File(FileAccessor.getImagePathName().getAbsolutePath() + "/" + imageName);
            if (!imageFile.exists()) {
                imageFile.createNewFile();
            }
            Uri imageUri = Uri.fromFile(imageFile);
            mIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        } catch (Exception e) {
            e.printStackTrace();
        }

        startActivityForResult(mIntent, REQUEST_IMAGE_CAMERA);
    }

    private void takePhoto() {
        Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
        openAlbumIntent.setType("image/*");
        startActivityForResult(openAlbumIntent, REQUEST_IMAGE_PHOTO);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.layout_back:
                finish();
                break;
            case R.id.layout_shortcut:
                break;
            case R.id.btn_invite_friend:
                intent.setClass(CreateNewGroup.this, InviteContactActivity.class);
                startActivityForResult(intent, REQUEST_CODE_INVITE_MEMBER);
                break;
            case R.id.new_group_icon:
//                createDialog();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_IMAGE_CAMERA:
                    String pathName = FileAccessor.getImagePathName().getAbsolutePath() + "/" + imageName;
                    if (mBitmap != null)
                        mBitmap.recycle();

                    mBitmap = BitmapFactory.decodeFile(pathName);
                    if (mBitmap != null) {
                        new_group_icon.setImageBitmap(mBitmap);
                    }
                    break;
                case REQUEST_IMAGE_PHOTO:
                    ContentResolver resolver = getContentResolver();
                    Uri originalUri = data.getData();
                    try {
                        if (mBitmap != null)
                            mBitmap.recycle();

                        mBitmap = MediaStore.Images.Media.getBitmap(resolver, originalUri);
                        if (mBitmap != null) {
                            new_group_icon.setImageBitmap(mBitmap);
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
    }

}
